package ext.tianma.workflow;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import wt.change2.ChangeException2;
import wt.change2.ChangeHelper2;
import wt.change2.Changeable2;
import wt.change2.WTChangeActivity2;
import wt.change2.WTChangeOrder2;
import wt.change2.WTChangeRequest2;
import wt.doc.WTDocument;
import wt.fc.ObjectReference;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.part.WTPart;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import ext.com.core.CoreUtil;
import ext.com.workflow.WorkflowUtil;

public class ECRWorkflowUtil {
	private static final String PASSIVE_ECR = ".Passive";
	private static final String DRAWING_DOC = ".DrawingDoc";
	private static final String INWORK_DOC = "INWORK";
	//原材料
	private static final String RAWMATERIAL = ".RawMaterial";
	//新品
	private static final String NEWPEODUCT = "NewProduct";
	private static final String NEWPEODUCT_MODIFY = "NewProductModify";
	//量产发布
	private static final String MASSPRODUCTION = "MassProductionRelease";
	private static final String MASSPRODUCTION_MODIFY = "MassProductionReleaseModify";
	//批准
	private static final String APPROVE_MODIFICATIONS = "APPROVE_MODIFICATIONS";
	private static final String APPROVAL= "APPROVAL";
	//已发布
	private static final String RELEASED = "RELEASED";
	//快速变更
	private static final String FAST_ECN= ".Fast_WTChangeOrder2";
	//创建ECN时生成的默认ECA的名称（默认）
	private static final String DEFAULT_ECA_NAME = "(Default task) Modify affected objects";
	//实施
	private static final String IMPLEMENTATION = "IMPLEMENTATION";
	
	/**
	 * 判断对象是不是ECR的软类型("无源类")
	 * @param object
	 * @return
	 */
	public static String checkECRType(Object object){
		String assessor = "";
		WTChangeRequest2 wc = null;
		if( object == null ){			
			return assessor;			
		}
		
		if( object instanceof ObjectReference ){			
			ObjectReference orf = ( ObjectReference )object;
			object = orf.getObject();			
		}
		
		if( object instanceof WTChangeRequest2 ){
			wc = ( WTChangeRequest2 ) object;
		}
		
		if( wc != null ){
			try {
				
				String type = ClientTypedUtility.getTypeIdentifier(wc).getTypename() ;
				
				if( ( type !=null ) && ( !type.contains( PASSIVE_ECR ) )){
					assessor = "Y";
				}
				
			} catch (WTException e) {
				e.printStackTrace();
			}
			
		}
		
		return assessor;
	}
	
	/**
	 * 根据给定的状态来设置ECN以及ECA的状态
	 * @param wc
	 * @param state
	 * @throws ChangeException2
	 * @throws WTException
	 */
	public static void setECNByECAState(WTChangeOrder2 wc , String state) throws ChangeException2, WTException{	
		
		if( wc != null ){
			
			WorkflowUtil.setLifeCycleState(wc, state);
			
			QueryResult qr = ChangeHelper2.service.getChangeActivities(wc);
			
			while (qr.hasMoreElements()) {
				Object object =  qr.nextElement();
				
				if( ( object != null ) && ( object instanceof ObjectReference ) ){
					ObjectReference obf = ( ObjectReference ) object;
					object = obf.getObject();
				}
				
				if( ( object != null ) && ( object instanceof WTChangeActivity2 ) ){
					WTChangeActivity2 wt = ( WTChangeActivity2 ) object;
					WorkflowUtil.setLifeCycleState(wt, state);
				}
			}
		}
		
	}
	
	/**
	 * 设置更改对象状态
	 * @param list
	 */
	public static void setObjsState( WTArrayList list ){
		System.out.println( "进入设置状态方法体!" );
		System.out.println( "查看收集对象是否为空:"+list.size() );
		if( ( list != null ) && ( list.size() > 0 ) ){
			for (int i = 0; i < list.size() ; i++) {
				
				Object object = list.get(i);
				
				if( object != null ){
					
					if( object instanceof ObjectReference ){
						
						ObjectReference orf = ( ObjectReference )object;
						object = orf.getObject();
						
					}
					
					if( object instanceof WTDocument ){
						WTDocument doc = ( WTDocument )object;
						if( doc != null ){
							setDocStates( doc );
						}						
					}else if( object instanceof WTPart ){
						
						WTPart part = ( WTPart )object;
						if( part != null ){							
							setPartStates( part );
						}
						
					}					
				}
			}			
		}		
	}
	
	/**
	 * 设置part状态
	 * @param doc  
	 * @param state
	 */
	private static void setPartStates( WTPart part ) {
		try {
			
			String type = ClientTypedUtility.getTypeIdentifier(part).getTypename();
			String state = part.getState().toString();
			System.out.println( "部件类型:"+type +"   状态:"+state);
			
			if( ( type!= null ) && ( type.contains( RAWMATERIAL ) ) && ( state.equals(APPROVE_MODIFICATIONS) ) ){
				WorkflowUtil.setLifeCycleState(part,APPROVAL);
			}else if( state.equals( NEWPEODUCT_MODIFY ) ){
				WorkflowUtil.setLifeCycleState(part, NEWPEODUCT);
			}else if( ( MASSPRODUCTION_MODIFY ).equals( state ) ){
				WorkflowUtil.setLifeCycleState( part , MASSPRODUCTION );
			}else if( ( INWORK_DOC ).equals( state ) ){
				WorkflowUtil.setLifeCycleState( part , NEWPEODUCT);
			}
			
		} catch (WTException e) {
			e.printStackTrace();
		}
	}	
	
	/**
	 * 设置doc状态
	 * @param doc
	 */
	private static void setDocStates( WTDocument doc ){
		if( doc != null ){
			String type = "" ;
			String state = "";
				
			if( doc != null ){
	
				state = doc.getState().toString();
			}
			System.out.println( "文档类型:"+type );
		
			if( (!state.equals("") ) && ( state.equals( INWORK_DOC ) ) ){
					
				try {
					WorkflowUtil.setLifeCycleState( doc , RELEASED );
				} catch (WTException e) {
					e.printStackTrace();
				}
					
			}
		}
	}
	
	/**
	 * 获取ECN中的ECA
	 * @param ecn
	 * @return
	 */
	public static List<WTChangeActivity2> addActivitieArraylist( WTChangeOrder2 ecn ){
		
		List<WTChangeActivity2> list = new ArrayList<WTChangeActivity2>();
		
		if( ecn != null ){
			try {
				//获取ECA
				QueryResult qr = ChangeHelper2.service.getChangeActivities(ecn);
				
				if( qr != null ){
					while( qr.hasMoreElements() ){
						Object object = qr.nextElement();
						
						if( object != null ){
							if( object instanceof WTChangeActivity2 ){
								WTChangeActivity2 eca = ( WTChangeActivity2 )object;
								list.add(eca);
							}
						}
						
					}
				}
			} catch (ChangeException2 e) {
				e.printStackTrace();
			} catch (WTException e) {
				e.printStackTrace();
			}
			
		}
		
		return list;
	}
	
	/**
	 * 获取ECN中ECA的所有产生的对象
	 * @param ecn
	 * @return
	 */
	public static WTArrayList addReviewObjs( WTChangeOrder2 ecn ){
		System.out.println( "进入收集对象法体!" );
		WTArrayList wlist = new WTArrayList();
		List<WTChangeActivity2> listeca = addActivitieArraylist( ecn );
		if( ( listeca != null ) && ( listeca.size()>0 ) ){
			
			for (int i = 0; i < listeca.size(); i++) {
				
				WTChangeActivity2 eca = listeca.get(i);
				if( eca != null ){
					
					try {
						//获取ECA中所有的产生的对象
						QueryResult qr = ChangeHelper2.service.getChangeablesAfter(eca);
						System.out.println( "开始获取eca中的产生对象:"+ qr );
						while ( (qr != null) && qr.hasMoreElements()) {
							Changeable2 changeable =  ( Changeable2 )qr.nextElement();
							System.out.println( "集合中的对象判断:"+ (!wlist.contains( changeable ) ) );
							if( ( wlist != null ) && (!wlist.contains( changeable ) ) ){
								wlist.add( changeable );
							}
							
						}
						
					} catch (ChangeException2 e) {
						e.printStackTrace();
					} catch (WTException e) {
						e.printStackTrace();
					}
					
				}				
			}		
		}		
		return wlist;		
	}
	
	/**
	 * 判断ecn是否是快速变更
	 * @param ecn
	 * @return
	 */
	public static String checkECNType( WTChangeOrder2 ecn ){
		String ecntypes = "" ;
		if( ecn != null ){
			
			try {
				
				String type = ClientTypedUtility.getTypeIdentifier( ecn ).getTypename();
				if( ( type != null ) && ( type.contains( FAST_ECN ) ) ){
					ecntypes="Y";
					return ecntypes;
				}
				
			} catch (WTException e) {
				e.printStackTrace();
			}finally{
				ecntypes = "S";
			}
			
		}
		return ecntypes;
	}
	
	/**
	 * 检查ECN中是否存在默认的ECA
	 * @param ecn
	 * @throws WTException 
	 */
	public static void checkDefaultActivitie( WTChangeOrder2 ecn ) throws WTException{
		
		if( ecn != null ){
			List< WTChangeActivity2 > activityList = addActivitieArraylist( ecn );
			
			if( activityList != null ){
				Iterator< WTChangeActivity2 > iterator = activityList.iterator();
				
				while ( iterator.hasNext() ) {
					WTChangeActivity2 eca = iterator.next();
					
					if( eca != null ){
						String activityName = eca.getName().trim();
						
						if( activityName.equals( DEFAULT_ECA_NAME ) ){
							throw new WTException("DCN中存在一个默认的DCA无法完成任务，请删除默认任务或修改默认任务的名称！");
						}
					}
				}
			}
		}
	}
	
	/**
	 * 设置ECN中所有ECA的状态到“实施状态”
	 * @param ecn
	 */
	public static void setActivitiesState( WTChangeOrder2 ecn ){
		
		if( ecn != null ){
			List< WTChangeActivity2 > activityList = addActivitieArraylist( ecn );
			
			if( activityList != null ){
				Iterator< WTChangeActivity2 > iterator = activityList.iterator();
				
				while ( iterator.hasNext() ) {
					WTChangeActivity2 eca = iterator.next();
					
					if( eca != null ){
						
						try {
							WorkflowUtil.setLifeCycleState(eca , IMPLEMENTATION);
						} catch (WTException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	
	public static void setActivitiesState(WTChangeOrder2 ecn, String state) {
		/**
		 * add by xucr on 20210126
		 * 此方法是从正式环境class反编译后加入的，
		 * 可能是提交者只发布了class，并未提交源文件
		 * */
		if ((ecn != null) && (state != null) && (!state.trim().isEmpty())) {
			List activityList = addActivitieArraylist(ecn);
			if (activityList != null) {
		        Iterator iterator = activityList.iterator();
		        while (iterator.hasNext()) {
		        	WTChangeActivity2 eca = (WTChangeActivity2)iterator.next();
	
		        	if (eca == null)
		            continue;
		        	try {
		        		WorkflowUtil.setLifeCycleState(eca, state);
		        	} catch (WTException e) {
		        		e.printStackTrace();
		        	}
		        }
			}
		}
	}
	
	/**
	 * 检查DCR中是否有相关联的的DCN
	 * @param ecr
	 * @return
	 */
	public static boolean checkChangeDCN( WTChangeRequest2 ecr ){
		boolean checkChangeDCN = false;
		
		if( ecr == null ){
			return checkChangeDCN;
		}
		
		try {
			//获取DCR中的所有的DCN
			QueryResult qr = ChangeHelper2.service.getChangeOrders(ecr);
			if( qr == null || qr.size() == 0 ){
				checkChangeDCN = true;
			}
			
		} catch (ChangeException2 e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
		
		return checkChangeDCN;
	}
	
	public static void main(String[] args) {
		
		if( args.length != 1  && args != null ){
			System.out.println( "参数错误!" );
			return;
		}
		
		try {
			WTObject wtobject = CoreUtil.getWTObjectByOid( args[0] );
			if( wtobject instanceof WTChangeOrder2 ){
				WTChangeOrder2 ecn = ( WTChangeOrder2 )wtobject;
				checkDefaultActivitie( ecn );
			}
		} catch (WTException e) {
			e.printStackTrace();
		}		
	}
	
}
